#include "database/disk_repository.h"
#include <QDebug>
#include <QSet>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>

DiskRepository::DiskRepository(QSqlDatabase &database, const QString &currentUserId)
    : m_database(database)
    , m_currentUserId(currentUserId)
{
}

bool DiskRepository::isDatabaseConnected() const
{
    return m_database.isOpen() && m_database.isValid();
}

KmsDisk DiskRepository::mapFromQuery(const QSqlQuery &query) const
{
    KmsDisk disk;
    disk.id = query.value("ID").toString();
    disk.type = query.value("TYPE").toInt();
    disk.name = query.value("NAME").toString();
    disk.domainId = query.value("DOMAIN_ID").toString();
    disk.ownerId = query.value("OWNER_ID").toString();
    disk.orderNo = query.value("ORDER_NO").toInt();
    disk.userId = query.value("USER_ID").toString();
    return disk;
}

bool DiskRepository::insert(const KmsDisk &disk)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return false;
    }
    
    QSqlQuery query(m_database);
    query.prepare("INSERT INTO kms_disk (ID, TYPE, NAME, DOMAIN_ID, OWNER_ID, ORDER_NO, USER_ID) "
                  "VALUES (?, ?, ?, ?, ?, ?, ?)");
    
    query.addBindValue(disk.id);
    query.addBindValue(disk.type);
    query.addBindValue(disk.name);
    query.addBindValue(disk.domainId);
    query.addBindValue(disk.ownerId);
    query.addBindValue(disk.orderNo);
    QString userId = disk.userId.isEmpty() ? m_currentUserId : disk.userId;
    query.addBindValue(userId);
    
    if (!query.exec()) {
        qDebug() << "插入网盘记录失败:" << query.lastError().text();
        return false;
    }
    
    return true;
}

bool DiskRepository::update(const KmsDisk &disk)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return false;
    }
    
    QSqlQuery query(m_database);
    query.prepare("UPDATE kms_disk SET TYPE=?, NAME=?, DOMAIN_ID=?, OWNER_ID=?, ORDER_NO=? "
                  "WHERE ID=?");
    
    query.addBindValue(disk.type);
    query.addBindValue(disk.name);
    query.addBindValue(disk.domainId);
    query.addBindValue(disk.ownerId);
    query.addBindValue(disk.orderNo);
    query.addBindValue(disk.id);
    
    if (!query.exec()) {
        qDebug() << "更新网盘记录失败:" << query.lastError().text();
        return false;
    }
    
    return true;
}

QList<KmsDisk> DiskRepository::findByName(const QString &name)
{
    QList<KmsDisk> disks;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return disks;
    }
    
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM kms_disk WHERE NAME LIKE ?");
    query.addBindValue("%" + name + "%");
    
    if (!query.exec()) {
        qDebug() << "查询网盘记录失败:" << query.lastError().text();
        return disks;
    }
    
    while (query.next()) {
        disks.append(mapFromQuery(query));
    }
    
    return disks;
}

QList<KmsDisk> DiskRepository::findAll()
{
    QList<KmsDisk> disks;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return disks;
    }
    
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM kms_disk");
    
    if (!query.exec()) {
        qDebug() << "查询所有网盘记录失败:" << query.lastError().text();
        return disks;
    }
    
    while (query.next()) {
        disks.append(mapFromQuery(query));
    }
    
    return disks;
}

bool DiskRepository::syncFromJson(const QJsonArray &disksData)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接，无法同步网盘数据";
        return false;
    }
    
    qDebug() << "开始同步网盘数据，数量:" << disksData.size();
    
    m_database.transaction();
    
    try {
        QSqlQuery insertQuery(m_database);
        insertQuery.prepare("INSERT INTO kms_disk (ID, TYPE, NAME, DOMAIN_ID, OWNER_ID, ORDER_NO, USER_ID) VALUES (?, ?, ?, ?, ?, ?, ?)");
        
        QSqlQuery updateQuery(m_database);
        updateQuery.prepare("UPDATE kms_disk SET TYPE=?, NAME=?, DOMAIN_ID=?, OWNER_ID=?, ORDER_NO=?, USER_ID=? WHERE ID=?");
        
        QSet<QString> existingDiskIds;
        QSqlQuery selectQuery(m_database);
        if (selectQuery.exec("SELECT ID FROM kms_disk")) {
            while (selectQuery.next()) {
                existingDiskIds.insert(selectQuery.value(0).toString());
            }
        }
        
        QSet<QString> newDiskIds;
        int insertCount = 0;
        int updateCount = 0;
        
        for (int i = 0; i < disksData.size(); ++i) {
            QJsonValue value = disksData[i];
            if (value.isObject()) {
                QJsonObject diskObj = value.toObject();
                
                KmsDisk disk;
                disk.id = diskObj["id"].toString();
                disk.type = diskObj["type"].toInt();
                disk.name = diskObj["name"].toString();
                disk.domainId = diskObj["domainId"].toString();
                disk.ownerId = diskObj["ownerId"].toString();
                disk.orderNo = diskObj["orderNo"].toInt();
                
                newDiskIds.insert(disk.id);
                
                qDebug() << "同步网盘 - ID:" << disk.id << "名称:" << disk.name << "类型:" << disk.type;
                
                if (existingDiskIds.contains(disk.id)) {
                    updateQuery.addBindValue(disk.type);
                    updateQuery.addBindValue(disk.name);
                    updateQuery.addBindValue(disk.domainId);
                    updateQuery.addBindValue(disk.ownerId);
                    updateQuery.addBindValue(disk.orderNo);
                    QString userId = disk.userId.isEmpty() ? m_currentUserId : disk.userId;
                    updateQuery.addBindValue(userId);
                    updateQuery.addBindValue(disk.id);
                    
                    if (updateQuery.exec()) {
                        updateCount++;
                        qDebug() << "成功更新网盘:" << disk.name;
                    } else {
                        qDebug() << "更新网盘失败:" << disk.name << "错误:" << updateQuery.lastError().text();
                    }
                } else {
                    insertQuery.addBindValue(disk.id);
                    insertQuery.addBindValue(disk.type);
                    insertQuery.addBindValue(disk.name);
                    insertQuery.addBindValue(disk.domainId);
                    insertQuery.addBindValue(disk.ownerId);
                    insertQuery.addBindValue(disk.orderNo);
                    QString userId = disk.userId.isEmpty() ? m_currentUserId : disk.userId;
                    insertQuery.addBindValue(userId);
                    
                    if (insertQuery.exec()) {
                        insertCount++;
                        qDebug() << "成功插入网盘:" << disk.name;
                    } else {
                        qDebug() << "插入网盘失败:" << disk.name << "错误:" << insertQuery.lastError().text();
                    }
                }
            }
        }
        
        QSqlQuery deleteQuery(m_database);
        deleteQuery.prepare("UPDATE kms_disk SET STATUS = -1 WHERE ID = ?");
        
        int deleteCount = 0;
        for (const QString &diskId : existingDiskIds) {
            if (!newDiskIds.contains(diskId)) {
                deleteQuery.addBindValue(diskId);
                if (deleteQuery.exec()) {
                    deleteCount++;
                    qDebug() << "逻辑删除网盘:" << diskId;
                }
            }
        }
        
        if (m_database.commit()) {
            qDebug() << "网盘数据同步完成 - 插入:" << insertCount << "更新:" << updateCount << "删除:" << deleteCount;
            return true;
        } else {
            qDebug() << "提交事务失败:" << m_database.lastError().text();
            m_database.rollback();
            return false;
        }
        
    } catch (...) {
        qDebug() << "同步网盘数据时发生异常";
        m_database.rollback();
        return false;
    }
}

